import { defineStore } from 'pinia'
export class Observer {
    name:string;
    cb: (message: string) => void;
    constructor(name:string,cb:(message:string)=>void) {
        this.name = name;
        this.cb = cb;
    }

    update(message:string) {
        // console.log(`${this.name} 收到通知: ${message}`);
        this.cb(message);
    }
}
class Subject {
    observers: Observer[] = [];
    constructor() {
        this.observers = [];
    }

    // 添加观察者
    attach(observer: Observer) {
        this.observers.push(observer);
    }

    // 移除观察者
    detach(observer: Observer) {
        const index = this.observers.indexOf(observer);
        if (index!== -1) {
            this.observers.splice(index, 1);
        }
    }

    // 通知所有观察者
    notify(message:string) {
        this.observers.forEach(observer => observer.update(message));
    }
}
export const useSubjectStore = defineStore('subject', () => {
    const subject = new Subject();
    function attach(observer: Observer) {
        subject.attach(observer);
    }
    function detach(observer: Observer) {
        subject.detach(observer);
    }
    function notify(message:string) {
        subject.notify(message);
    }
    return {
        attach,
        detach,
        notify,
    }
})
